<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>Springboot学习笔记 | 耀的个人站</title>
  <meta name="description" content="Springboot学习笔记一、实例1：使用Springboot输出“Hello World！”1、pom.xml1234567&lt;!--Web；springboot会自动配置web环境（配置Tomcat、WebMVC、Validator、JSON等）--&gt;&lt;dependency&gt;    &lt;groupId&gt;org.springframework.boot&lt;&#x2F;">
<meta property="og:type" content="article">
<meta property="og:title" content="Springboot学习笔记">
<meta property="og:url" content="https://giscloud.ltd/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="耀的个人站">
<meta property="og:description" content="Springboot学习笔记一、实例1：使用Springboot输出“Hello World！”1、pom.xml1234567&lt;!--Web；springboot会自动配置web环境（配置Tomcat、WebMVC、Validator、JSON等）--&gt;&lt;dependency&gt;    &lt;groupId&gt;org.springframework.boot&lt;&#x2F;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://giscloud.ltd/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011184319065.png">
<meta property="og:image" content="https://giscloud.ltd/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011174643868.png">
<meta property="og:image" content="https://giscloud.ltd/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011174711784.png">
<meta property="og:image" content="https://giscloud.ltd/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011174734925.png">
<meta property="og:image" content="https://giscloud.ltd/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011174800640.png">
<meta property="article:published_time" content="2021-10-11T09:10:07.000Z">
<meta property="article:modified_time" content="2021-10-12T01:07:40.985Z">
<meta property="article:author" content="zhaoyao">
<meta property="article:tag" content="springboot">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://giscloud.ltd/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011184319065.png">
  <!-- Canonical links -->
  <link rel="canonical" href="https://giscloud.ltd/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/index.html">
  
    <link rel="alternate" href="/atom.xml" title="耀的个人站" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/css/style.css">

  
  
  
    <link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.3.5/dist/jquery.fancybox.min.css" rel="stylesheet">
  
  
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1.4.0/dist/gitalk.min.css">
  
<meta name="generator" content="Hexo 5.4.0"></head>


<body class="main-center theme-blue" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://github.com/geiao223" target="_blank">
          <img class="img-circle img-rotate" src="/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">耀</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">GIS Developer</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> nanjing, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav ">
        
        
        <li class="menu-item menu-item-home">
          <a href="/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      <head>
    <meta charset="utf-8">
    
      
            
        
            
        
            
        
            
              <link rel="stylesheet" href="//at.alicdn.com/t/font_557201_kt8eehtlfzr.css">
            
        
            
        
    
</head>

	
    <ul class="social-links">
    	
            
                <li><a href="https://github.com/geiao223" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
            
             
        
            
                <li><a href="https://gitee.com/geiao2" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
            
             
        
            
                <li><a href="https://www.zhihu.com/people/geiao1314/columns" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
            
             
        
            
            
                <li><a href="https://space.bilibili.com/315638226" target="_blank" title="Bilibili" data-toggle=tooltip data-placement=top><i class="iconfont icon-bilibili-line"></i></a></li>
             
        
            
                <li><a href="https://mail.google.com/mail/u/0/?fs=1&tf=cm&source=mailto&to=zhaoyao92@qq.com" target="_blank" title="Email" data-toggle=tooltip data-placement=top><i class="icon icon-email"></i></a></li>
            
             
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎交流与分享经验!</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/openstack/">OpenStack</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/springboot/">springboot</a><span class="category-list-count">3</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/openstack/" rel="tag">OpenStack</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/cas/" rel="tag">cas</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/springboot/" rel="tag">springboot</a><span class="tag-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/tags/openstack/" style="font-size: 13px;">OpenStack</a> <a href="/tags/cas/" style="font-size: 14px;">cas</a> <a href="/tags/springboot/" style="font-size: 13px;">springboot</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/12/">十二月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/10/">十月 2021</a><span class="archive-list-count">4</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/openstack/">OpenStack</a>
              </p>
              <p class="item-title">
                <a href="/2021/12/31/openstack%E5%AE%9E%E6%88%98/" class="title">OpenStack-T版搭建笔记</a>
              </p>
              <p class="item-date">
                <time datetime="2021-12-30T23:33:07.000Z" itemprop="datePublished">2021-12-31</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/springboot/">springboot</a>
              </p>
              <p class="item-title">
                <a href="/2021/10/15/5-0-x%E7%94%A8%E6%88%B7%E7%95%8C%E9%9D%A2%E5%AE%9A%E5%88%B6/" class="title">5.0.x用户界面定制</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-15T01:04:03.000Z" itemprop="datePublished">2021-10-15</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/springboot/">springboot</a>
              </p>
              <p class="item-title">
                <a href="/2021/10/13/cas/" class="title">CAS</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-13T06:42:14.000Z" itemprop="datePublished">2021-10-13</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/springboot/">springboot</a>
              </p>
              <p class="item-title">
                <a href="/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="title">Springboot学习笔记</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-11T09:10:07.000Z" itemprop="datePublished">2021-10-11</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/2021/10/11/test/" class="title">Test</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-11T07:00:19.000Z" itemprop="datePublished">2021-10-11</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">文章目录</h3>
      <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0"><span class="toc-number">1.</span> <span class="toc-text">Springboot学习笔记</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%AE%9E%E4%BE%8B1%EF%BC%9A%E4%BD%BF%E7%94%A8Springboot%E8%BE%93%E5%87%BA%E2%80%9CHello-World%EF%BC%81%E2%80%9D"><span class="toc-number">1.1.</span> <span class="toc-text">一、实例1：使用Springboot输出“Hello World！”</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81pom-xml"><span class="toc-number">1.1.1.</span> <span class="toc-text">1、pom.xml</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81Controller%E5%B1%82"><span class="toc-number">1.1.2.</span> <span class="toc-text">2、Controller层</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E5%85%A5%E5%8F%A3%E7%B1%BB"><span class="toc-number">1.1.3.</span> <span class="toc-text">3、入口类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E9%A1%B9%E7%9B%AE%E6%89%93%E5%8C%85%E6%88%90%E5%8F%AF%E6%89%A7%E8%A1%8C%E7%9A%84JAR%E5%8C%85"><span class="toc-number">1.2.</span> <span class="toc-text">二、项目打包成可执行的JAR包</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81idea%E5%BF%85%E4%BC%9A%E5%BF%AB%E6%8D%B7%E9%94%AE%E4%B8%8E%E8%AE%BE%E7%BD%AE"><span class="toc-number">1.3.</span> <span class="toc-text">三、idea必会快捷键与设置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9B%E3%80%81Springboot%E8%87%AA%E5%8A%A8%E9%85%8D%E7%BD%AE"><span class="toc-number">1.4.</span> <span class="toc-text">四、Springboot自动配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%94%E3%80%81Springboot%E7%83%AD%E9%83%A8%E7%BD%B2"><span class="toc-number">1.5.</span> <span class="toc-text">五、Springboot热部署</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%AD%E3%80%81%E5%AE%9E%E4%BE%8B2%EF%BC%9A%E5%AE%9A%E5%88%B6%E5%90%AF%E5%8A%A8%E7%94%BB%E9%9D%A2"><span class="toc-number">1.6.</span> <span class="toc-text">六、实例2：定制启动画面</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%83%E3%80%81Springboot%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.7.</span> <span class="toc-text">七、Springboot常用注解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E7%B3%BB%E7%BB%9F%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.7.1.</span> <span class="toc-text">1、系统注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.7.2.</span> <span class="toc-text">2、常用注解</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%9C%A8%E7%B1%BB%E5%90%8D%E4%B8%8A%E7%9A%84%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.7.2.1.</span> <span class="toc-text">使用在类名上的注解</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%9C%A8%E6%96%B9%E6%B3%95%E4%B8%8A%E7%9A%84%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.7.2.2.</span> <span class="toc-text">使用在方法上的注解</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E5%85%B6%E5%AE%83%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.7.3.</span> <span class="toc-text">3、其它注解</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%AB%E3%80%81%E4%BD%BF%E7%94%A8%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-number">1.8.</span> <span class="toc-text">八、使用配置文件</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81%E4%BD%BF%E7%94%A8YAML%E9%85%8D%E7%BD%AE%E6%96%B9%E5%BC%8F%E6%97%B6%E9%9C%80%E8%A6%81%E6%B3%A8%E6%84%8F%E4%B8%80%E4%B8%8B%E5%87%A0%E7%82%B9%EF%BC%9A"><span class="toc-number">1.8.0.1.</span> <span class="toc-text">1、使用YAML配置方式时需要注意一下几点：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B3%EF%BC%9A%E6%BC%94%E7%A4%BA%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8application-yml%E6%96%87%E4%BB%B6"><span class="toc-number">1.8.0.2.</span> <span class="toc-text">实例3：演示如何使用application.yml文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B4%EF%BC%9A%E6%BC%94%E7%A4%BA%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8application-priperties%E6%96%87%E4%BB%B6"><span class="toc-number">1.8.0.3.</span> <span class="toc-text">实例4：演示如何使用application.priperties文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B5%EF%BC%9A%E9%85%8D%E7%BD%AE%E5%A4%9A%E7%8E%AF%E5%A2%83"><span class="toc-number">1.8.0.4.</span> <span class="toc-text">实例5：配置多环境</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B9%9D%E3%80%81%E5%B8%B8%E7%94%A8%E7%9A%84starter"><span class="toc-number">1.9.</span> <span class="toc-text">九、常用的starter</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B002"><span class="toc-number">2.</span> <span class="toc-text">Springboot学习笔记02</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E4%BD%BF%E7%94%A8Thymeleaf"><span class="toc-number">2.1.</span> <span class="toc-text">一、使用Thymeleaf</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81thymeleaf%E5%9F%BA%E7%A1%80%E8%AF%AD%E6%B3%95"><span class="toc-number">2.2.</span> <span class="toc-text">二、thymeleaf基础语法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B6%EF%BC%9A%E7%BC%96%E5%86%99Thymeleaf%E8%A7%86%E5%9B%BE%E4%BB%A5%E5%B1%95%E7%A4%BA%E6%95%B0%E6%8D%AE"><span class="toc-number">2.2.1.</span> <span class="toc-text">实例6：编写Thymeleaf视图以展示数据</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E4%BD%BF%E7%94%A8%E6%8E%A7%E5%88%B6%E5%99%A8"><span class="toc-number">2.3.</span> <span class="toc-text">三、使用控制器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3%E5%8F%8AURL%E6%98%A0%E5%B0%84%EF%BC%88%E7%AA%84%E5%8C%96%E6%98%A0%E5%B0%84%EF%BC%89"><span class="toc-number">2.3.1.</span> <span class="toc-text">1、常用注解及URL映射（窄化映射）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%A4%84%E7%90%86HTTP%E8%AF%B7%E6%B1%82%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-number">2.3.2.</span> <span class="toc-text">2、处理HTTP请求的方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E5%A4%84%E7%90%86%E5%86%85%E5%AE%B9%E7%B1%BB%E5%9E%8B"><span class="toc-number">2.3.3.</span> <span class="toc-text">3、处理内容类型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#3-1%E3%80%81%E8%AE%A4%E8%AF%86HTTP%E4%B8%AD%E7%9A%84%E5%AA%92%E4%BD%93%E7%B1%BB%E5%9E%8BContent-Type"><span class="toc-number">2.3.3.1.</span> <span class="toc-text">3.1、认识HTTP中的媒体类型Content-Type</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-2%E3%80%81%E4%BD%BF%E7%94%A8Produces%E5%92%8CConsumes%E5%A4%84%E7%90%86%E5%86%85%E5%AE%B9%E7%B1%BB%E5%9E%8B"><span class="toc-number">2.3.3.2.</span> <span class="toc-text">3.2、使用Produces和Consumes处理内容类型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3%E3%80%81%E5%9C%A8%E6%96%B9%E6%B3%95%E4%B8%AD%E4%BD%BF%E7%94%A8%E5%8F%82%E6%95%B0"><span class="toc-number">2.3.3.3.</span> <span class="toc-text">3.3、在方法中使用参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-4%E3%80%81%E5%AE%9E%E4%BE%8B7-%E5%AE%9E%E7%8E%B0MVC%E6%A8%A1%E5%BC%8F%E7%9A%84Web%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F"><span class="toc-number">2.3.3.4.</span> <span class="toc-text">3.4、实例7:实现MVC模式的Web应用程序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-5%E3%80%81%E5%AE%9E%E4%BE%8B8%EF%BC%9A%E9%AA%8C%E8%AF%81%E8%A1%A8%E5%8D%95%E6%95%B0%E6%8D%AE%E5%B9%B6%E5%AE%9E%E7%8E%B0%E6%95%B0%E6%8D%AE%E7%9A%84%E8%87%AA%E5%AE%9A%E4%B9%89%E9%AA%8C%E8%AF%81"><span class="toc-number">2.3.3.5.</span> <span class="toc-text">3.5、实例8：验证表单数据并实现数据的自定义验证</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B003"><span class="toc-number">3.</span> <span class="toc-text">springboot学习笔记03</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%93%8D%E5%BA%94%E5%BC%8F%E7%BC%96%E7%A8%8B"><span class="toc-number">3.1.</span> <span class="toc-text">一、响应式编程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E5%AE%9E%E4%BE%8B12%EF%BC%9A%E7%94%A8WebFlux%E6%A8%A1%E5%BC%8F%E6%93%8D%E4%BD%9CMongoDB%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%8C%E5%AE%9E%E7%8E%B0%E6%95%B0%E6%8D%AE%E7%9A%84%E5%A2%9E%E5%8A%A0%E3%80%81%E5%88%A0%E9%99%A4%E3%80%81%E4%BF%AE%E6%94%B9%E5%92%8C%E6%9F%A5%E8%AF%A2%E5%8A%9F%E8%83%BD"><span class="toc-number">3.2.</span> <span class="toc-text">二、实例12：用WebFlux模式操作MongoDB数据库，实现数据的增加、删除、修改和查询功能</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E4%B8%8B%E8%BD%BD%E5%AE%89%E8%A3%85MongoDB-4-4-4-%E4%BB%A5%E5%8F%8Aoto-3T-1-4"><span class="toc-number">3.2.1.</span> <span class="toc-text">1、下载安装MongoDB 4.4.4 以及oto 3T -1.4</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%88%9B%E5%BB%BA%E7%94%A8%E6%88%B7%E5%90%8D%E3%80%81%E5%AF%86%E7%A0%81%E5%8F%8A%E6%95%B0%E6%8D%AE%E5%BA%93%E8%A1%A8"><span class="toc-number">3.2.2.</span> <span class="toc-text">2、创建用户名、密码及数据库表</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81pom-xml%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="toc-number">3.2.3.</span> <span class="toc-text">3、pom.xml添加依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E4%B8%AD%E6%B7%BB%E5%8A%A0%E8%BF%9E%E6%8E%A5"><span class="toc-number">3.2.4.</span> <span class="toc-text">4、配置文件中添加连接</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81entity%E2%86%92User-java"><span class="toc-number">3.2.5.</span> <span class="toc-text">5、entity→User.java</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6%E3%80%81repository%E2%86%92UserRepository-java"><span class="toc-number">3.2.6.</span> <span class="toc-text">6、repository→UserRepository.java</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7%E3%80%81controller%E2%86%92UserWebFluxController"><span class="toc-number">3.2.7.</span> <span class="toc-text">7、controller→UserWebFluxController</span></a></li></ol></li></ol></li></ol>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <div class="content">
  <article id="post-springboot学习笔记" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      Springboot学习笔记
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="article-date">
	  <time datetime="2021-10-11T09:10:07.000Z" itemprop="datePublished">2021-10-11</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/categories/springboot/">springboot</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/tags/springboot/" rel="tag">springboot</a>
  </span>


        

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/#comments" class="article-comment-link">评论</a></span>
        
	
		<span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 7.1k(字)</span>
	
	
		<span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 31(分)</span>
	

      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <h1 id="Springboot学习笔记"><a href="#Springboot学习笔记" class="headerlink" title="Springboot学习笔记"></a>Springboot学习笔记</h1><h2 id="一、实例1：使用Springboot输出“Hello-World！”"><a href="#一、实例1：使用Springboot输出“Hello-World！”" class="headerlink" title="一、实例1：使用Springboot输出“Hello World！”"></a>一、实例1：使用Springboot输出“Hello World！”</h2><h3 id="1、pom-xml"><a href="#1、pom-xml" class="headerlink" title="1、pom.xml"></a>1、pom.xml</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--Web；springboot会自动配置web环境（配置Tomcat、WebMVC、Validator、JSON等）--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="2、Controller层"><a href="#2、Controller层" class="headerlink" title="2、Controller层"></a>2、Controller层</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span> <span class="comment">//代表这个类是REST风格的控制器，返回JSON/XML类型的数据</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldController</span> </span>&#123;</span><br><span class="line">    <span class="meta">@RequestMapping(&quot;/Hello&quot;)</span> <span class="comment">//配置URL和方法之间的映射。可注解在类和方法上。注解在方法上的@RequestMapping路径会继承注解在类上的路径</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">hello</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Hello.Spring boot!&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3、入口类"><a href="#3、入口类" class="headerlink" title="3、入口类"></a>3、入口类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span> <span class="comment">//表示这个是spring boot项目的入口类</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldApplication</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		SpringApplication.run(HelloWorldApplication.class, args);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="二、项目打包成可执行的JAR包"><a href="#二、项目打包成可执行的JAR包" class="headerlink" title="二、项目打包成可执行的JAR包"></a>二、项目打包成可执行的JAR包</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"># 使用Maven中的package将项目打包为JAR包</span><br><span class="line"># 如果报错：Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0；则需要修改maven-resources-plugin的版本</span><br><span class="line"><span class="tag">&lt;<span class="name">plugin</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.maven.plugins<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>maven-resources-plugin<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.4.3<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">plugin</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="三、idea必会快捷键与设置"><a href="#三、idea必会快捷键与设置" class="headerlink" title="三、idea必会快捷键与设置"></a>三、idea必会快捷键与设置</h2><p>快捷键设置的位置：“File→Settings→keymap→Main Menu→Code→Completion”</p>
<p><strong>1、Ctrl+Space</strong>：实现快捷提示</p>
<p><strong>2、Ctrl+Shift+Space</strong>：基于上下文环境智能匹配使用的方法</p>
<p><strong>3、Ctrl+P：</strong>自动提示参数</p>
<p><strong>4、实现自定义转义：</strong>Alt+Enter→Inject Ianguage→Inject language or reference(并按Enter)→JSON→Edit JSON Fragment→输入要转义的JSON值。如果要退出编辑JSON信息的视图，则按“Ctrl+F4”快捷键。</p>
<p><strong>5、自定义高复用代码块（Live Template）</strong></p>
<p>设置自定义代码操作方式：“File→Settings→Editor→Live Template→+”在弹出的窗口中就可以自定义代码块了。</p>
<p>abbreviation代表添加缩写语句，比如psvm</p>
<p>Description代表描述信息，以便后期查询</p>
<p>Template text代表要复制的代码</p>
<ul>
<li>sout：可以快速生成“System.out.println()”</li>
<li>soutm:可以快速输出当前类和方法名：“System.out.println(hello.hello)”</li>
<li>psfs:可以快速输出“public static final String”</li>
<li>fori：可以快速输出“for(int i = 0; i &lt;; i++){}”</li>
<li>ifn: 可以快速输出“if(args== null){}”</li>
</ul>
<p><strong>6、设置注释信息</strong></p>
<p>“File→Settings→Editor→File and Code Template→includes→File Header”</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  *Copyright(C)，2021-$&#123;YEAR&#125;),国兴环保</span></span><br><span class="line"><span class="comment">  *FileName:$&#123;NAME&#125;</span></span><br><span class="line"><span class="comment">  *Author:  ZY</span></span><br><span class="line"><span class="comment">  *Date:    $&#123;DATE&#125;$&#123;TIME&#125;</span></span><br><span class="line"><span class="comment">  *Description:$&#123;DESCRIPTION&#125;</span></span><br><span class="line"><span class="comment">  *history:</span></span><br><span class="line"><span class="comment">  *&lt;author&gt;     &lt;time&gt;      &lt;version&gt;   &lt;desc&gt;</span></span><br><span class="line"><span class="comment">  *作者姓名     修改时间    版本号      描述</span></span><br><span class="line"><span class="comment">  */</span></span><br></pre></td></tr></table></figure>

<p><strong>7、”Alt+Enter“快捷键</strong></p>
<p><strong>8、全局JDK、全局Maven、全局版本控制Git/Svn</strong></p>
<p><strong>9、自动导包与智能移除</strong></p>
<p><strong>10、自动生成语句</strong></p>
<p>声明完参数后，参数后面接着输入“.notnull”并按“Enter”，idea就自动生成if语句。</p>
<p>在变量后面直接跟上for、sout、switch等表达式，idea会直接转换成相应的语句。</p>
<p><strong>11、快速生成try/catch、if/else代码</strong></p>
<p>ctrl+Alt+T快捷键</p>
<p><strong>12、快速生成构造器，以及Getter/Setter、Override方法</strong></p>
<p>在实体编辑窗口中，使用“Alt+Insert”快捷键</p>
<h2 id="四、Springboot自动配置"><a href="#四、Springboot自动配置" class="headerlink" title="四、Springboot自动配置"></a>四、Springboot自动配置</h2><ul>
<li><p>自动配置通过注解@EnableAutoConfiguration来实现的，具有非入侵性。</p>
</li>
<li><p>在Idea中通过“Run→EditConfigurations→设置Program arguments参数为“–debug”。在启动应用程序之后即可在控制台中看到条件评估报告（即当前有哪些自动配置）</p>
</li>
<li><p>如果不需要某些自动配置，则可以通过注解@EnableAutoConfiguration的“exclude 或excludeName”属性来指定，或者在配置文件（application.properties或application.yml）中指定“spring.autoconfigure.exclude”的值。</p>
</li>
</ul>
<h2 id="五、Springboot热部署"><a href="#五、Springboot热部署" class="headerlink" title="五、Springboot热部署"></a>五、Springboot热部署</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 添加热部署依赖,该依赖在项目打包时会被禁用。如果项目中使用了Redis作为缓存，则禁止使用热部署，以免出现类型转换等问题。--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-devtools<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="六、实例2：定制启动画面"><a href="#六、实例2：定制启动画面" class="headerlink" title="六、实例2：定制启动画面"></a>六、实例2：定制启动画面</h2><p>1、自定义Banner</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$&#123;AnsiColor.BRIGHT_RED&#125; //设置控制台中输出内容的颜色，具体参考org.springframework.boot.ansi.AnsiColor</span><br><span class="line">application.version:$&#123;application.version&#125; //用来获取MANIFEST.MF文件中的版本号 V2.4.4获取不到值</span><br><span class="line">spring−boot.formatted.version:$&#123;application.formatted-version&#125; //格式化后的&#123;application.version&#125;版本信息 V2.4.4获取不到值</span><br><span class="line">spring−boot.version:$&#123;spring-boot.version&#125;  //Springboot的版本号</span><br><span class="line">spring-boot.formatted-version:$&#123;spring-boot.formatted-version&#125; //格式化后的&#123;spring-boot.version&#125;版本信息</span><br></pre></td></tr></table></figure>

<h2 id="七、Springboot常用注解"><a href="#七、Springboot常用注解" class="headerlink" title="七、Springboot常用注解"></a>七、Springboot常用注解</h2><h3 id="1、系统注解"><a href="#1、系统注解" class="headerlink" title="1、系统注解"></a>1、系统注解</h3><ul>
<li>@Override : 用于修饰方法，表示此方法重写了父类方法</li>
<li>@Deprecated：用于修饰方法，表述此方法已过时。经常在版本升级后会遇到</li>
<li><strong>@SuppressWarnnings</strong>：告诉编译器忽视某类编译警告</li>
</ul>
<p><strong>@SuppressWarnnings</strong>注解，它有一下几种属性</p>
<ul>
<li>unchecked：未检查的转化</li>
<li>unused：未使用的变量</li>
<li>resource：泛型，即未指定类型</li>
<li>path：在类中的路径。原文件路径中有不存在的路径</li>
<li>deprecation：使用了某些不赞成使用的类和方法</li>
<li>fallthrough：switch语句执行到底，不会遇到break关键字</li>
<li>serial：实现Serialzable，但是未定义serialVersionUID</li>
<li>rawtypes：没有传递带有泛型的参数</li>
<li>all：代表全部类型的警告</li>
</ul>
<h3 id="2、常用注解"><a href="#2、常用注解" class="headerlink" title="2、常用注解"></a>2、常用注解</h3><h4 id="使用在类名上的注解"><a href="#使用在类名上的注解" class="headerlink" title="使用在类名上的注解"></a>使用在类名上的注解</h4><ul>
<li>RestController：作用相当于@ResponseBody加@Controller</li>
<li>Controller：声明此类是一个springMVC Controller对象</li>
<li>@service：声明一个业务处理类（实现非接口类）</li>
<li>@Repository：声明一个数据库访问类（实现非接口类）</li>
<li>@Component：代表其是Spring管理类，常用在无法用@service、@Repository描述的Spring管理的类上，相当于通用的注解。它用于把普通POJO（简单的java对象）实例化到Spring容器中。当类不属于注解@controller和@Service等时，就可以使用注解@Component来标注这个类</li>
<li>@Configuration：声明此类是一个配置类，常与@Bean配合使用。它作为Bean的载体，用来指示一个类声明、一个或多个@Bean方法，在运行时为这些Bean生成BeanDefinition和服务请求。</li>
</ul>
<p>使用在类名上、属性或构造函数参数上的注解</p>
<ul>
<li>@Resource：默认按byName自动注入。@Autowired与@Resource都可以用来装配@Bean，也都可以写在字段上或setter方法上。</li>
<li>@Autowired：默认按byName自动注入。它表示被修饰的类需要注入对象。Spring会扫描所有被@Autowired标注的类，然后根据类型在IoC容器中找到匹配的类进行注入。被@Autowired注解后的类不需要再导入文件。</li>
</ul>
<p>使用在类名或方法上的注解</p>
<ul>
<li>@RequestMapping：如果用在类上，则表示所有响应请求的方法的都是以该地址作为父路径的。该注解有6个属性。<strong>Params：</strong>指定Request中必须包含某些参数值，才让该方法处理。<strong>Headers：</strong>指定Request中必须包含某些指定的header值，才能让该方法处理请求。<strong>Value：</strong>指定请求的实际地址，指定的地址可以是URI Template模式。<strong>Method：</strong>指定请求的Method类型，如GET、POST、PUT、DELETE等。<strong>Consumes：</strong>指定处理请求的提交内容类型Content-Type，如“application/json,text/html”。<strong>Produces：</strong>指定返回的内容类型。只有当Request请求头中的Accept类型中包含该指定类型时才返回。</li>
<li>@Transactional：用于处理事务。它可以用在接口、接口方法、类及类方法上。但Spring不建议在接口或者接口方法上使用该注解。因为该注解只有在使用基于接口的代理时才会生效。如果异常被捕获（try{} catch{}）了，则事务就不会滚了。如果想让事务回滚，则必须再往外抛出异常（try{} catch{ throw Exception}）。</li>
</ul>
<p>使用在类名或属性上的注解</p>
<ul>
<li>@Qualifier：为Bean指定名称，随后再通过名字引用Bean。常于@Autowired一起使用。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldBMvcController</span></span>&#123;</span><br><span class="line">    <span class="meta">@RequestMapping(&quot;helloworldB&quot;)</span></span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">helloWorld</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Hello,Spring Boot!&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**  * Description:标注为服务类  */</span><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ArticleServiceImpl</span> <span class="keyword">implements</span> <span class="title">ArticleService</span></span>&#123;    <span class="meta">@Autowired</span>    <span class="keyword">private</span> ArticleRepository articleRepository;    <span class="comment">/**     * Description:重写service接口的实现，实现根据id查询对象功能     * <span class="doctag">@param</span> id     * <span class="doctag">@return</span>     */</span>    <span class="meta">@Override</span>    <span class="function"><span class="keyword">public</span> Article <span class="title">findArticleById</span><span class="params">(<span class="keyword">long</span> id)</span></span>&#123;        <span class="keyword">return</span> articleRepository.findById(id);    &#125;&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ArticleController</span></span>&#123;    <span class="meta">@Resource</span>    <span class="keyword">private</span> ArticleRepository articleRepository;    <span class="comment">/**     * Description:新增保存方法     */</span>    <span class="meta">@PostMapping(&quot;&quot;)</span>    <span class="function"><span class="keyword">public</span> String <span class="title">saveArticle</span><span class="params">(Article model)</span></span>&#123;        articleRepository.save(model);        <span class="keyword">return</span> <span class="string">&quot;redirect:/article/&quot;</span>;    &#125;&#125;</span><br></pre></td></tr></table></figure>

<h4 id="使用在方法上的注解"><a href="#使用在方法上的注解" class="headerlink" title="使用在方法上的注解"></a>使用在方法上的注解</h4><p>使用在方法参数前</p>
<ul>
<li>@RequestBody：常用来处理application/json、application/xml等Content-Type类型的数据，意味着HTTP消息是JSON/XML格式，需将其转化为指定类型参数</li>
<li>@PathVariable：将URL获取的参数映射到方法参数上</li>
</ul>
<p>使用在方法上</p>
<ul>
<li>@Bean：声明改方法的返回结果是一个由Spring容器管理的Bean。用于封装数据，一般有Setter、Getter方法。在MVC模型中，对应的是M（模型）。</li>
<li>@ResponseBody：通过适当的HttpMessageConverter将控制器中方法返回的对象转换为指定格式（JSON/XML）后，写入Response对象的Body数据区</li>
</ul>
<p><strong>举例：用AJAX（前端）提交数据，然后在控制器（后端）接收数据</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(&#123;    <span class="attr">url</span>:<span class="string">&quot;/post&quot;</span>,    <span class="attr">type</span>:<span class="string">&quot;POST&quot;</span>,    <span class="attr">data</span>:<span class="string">&#x27;&#123;&quot;name&quot;:&quot;geiao&quot;&#125;&#x27;</span>,    <span class="attr">contentType</span>:<span class="string">&quot;application/json charset=utf-8&quot;</span>    success:<span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;        alert(<span class="string">&quot;request success!&quot;</span>);    &#125;&#125;)</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@requestMapping(&quot;/post&quot;)</span><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">psot</span><span class="params">(<span class="meta">@requestBody</span> String name)</span></span>&#123;    <span class="comment">//省略&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="3、其它注解"><a href="#3、其它注解" class="headerlink" title="3、其它注解"></a>3、其它注解</h3><p>使用在入口类/类名上的注解</p>
<ul>
<li>@EnableAutoConfiguration：用来提供自动装配</li>
<li>@SpringBootApplication：用来启动入口类Application</li>
<li>@EnableScheduling：用来开启计划任务。spring通过@Scheduled支持多种类型的计划任务，包括cron、fixDelay、fixRate等</li>
<li>@EnableAsync：用来开启异步注解功能</li>
<li>@ComponentScan：用来扫描组件，可自动发现和装配一些Bean。它根据定义的扫描路径，把符合扫描规则的类装配到Spring容器中，告诉Spring哪个包（package）的类会被spring自动扫描并且装入IoC容器。它对应XML配置中的元素。可以通过basePackages等熟悉来细粒度地定制自动扫描的范围，默认会从声明@ComponentScan所在类的包进行扫描。</li>
<li>@Aspec：标注切面，可以用来配置事务、日志、权限验证，在用户请求时做一些处理等。</li>
</ul>
<p>使用在类上的注解</p>
<ul>
<li>@ControllerAdvice：包含@Component，可以被扫描到。统一处理异常。</li>
<li>@ExceptionHandler：用在方法上，表示遇到这个异常就执行该方法。</li>
<li>@Value：用在属性上，用于获取配置文件中的值。</li>
</ul>
<h2 id="八、使用配置文件"><a href="#八、使用配置文件" class="headerlink" title="八、使用配置文件"></a>八、使用配置文件</h2><p>Springboot支持使用Properties和YANL两种配置方式，Properties的优先级要高于YAML。</p>
<h4 id="1、使用YAML配置方式时需要注意一下几点："><a href="#1、使用YAML配置方式时需要注意一下几点：" class="headerlink" title="1、使用YAML配置方式时需要注意一下几点："></a>1、使用YAML配置方式时需要注意一下几点：</h4><ul>
<li>原来以“.”分隔的key会变成树状结构。例如，“server.port=8080”会变成：</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">server:	port: 8080</span><br></pre></td></tr></table></figure>

<ul>
<li>在key后面的冒号后一定要跟一个空格</li>
<li>如果把原有的application.properties删除，则建议执行一下“maven -X clean install”命令YAML格式不支持用注解@PropertySource导入配置</li>
</ul>
<p><strong>可以在线对Properties和YAML文件内容进行互转 <a target="_blank" rel="noopener" href="https://www.toyaml.com/index.html">https://www.toyaml.com/index.html</a></strong></p>
<h4 id="实例3：演示如何使用application-yml文件"><a href="#实例3：演示如何使用application-yml文件" class="headerlink" title="实例3：演示如何使用application.yml文件"></a>实例3：演示如何使用application.yml文件</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"># 关闭自定义的Banner模式# spring.main.banner-mode = off# 定义服务器的配置# port定义要访问的端口# &quot;timeout: 30&quot;:定义Session的超时时间是30s# &quot;uri-encoding: UTF-8&quot;:定义URI编码是UTF-8格式server:  port: 8090  servlet:    session:      timeout: 30    tmocat:      uri-encoding: UTF-8age: 18name: zhaoyaopersoninfo:  name: geiao  age: 30</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span> <span class="comment">//声明此类是Spring管理类。它常用在无法用@Service、@Repository描述的Spring管理类上，相当于通用的注解@ConfigurationProperties(prefix=&quot;personinfo&quot;) // 把同类配置信息自动封装成一个实体类。其属性prefix代表配置文件中配置项的前缀，如在配置文件中定义的“personinfo”public class GetPersonInfoProperties &#123;    private String name;    private int age;    public String getName()&#123;        return name;    &#125;    public void setName(String name)&#123;        this.name = name;    &#125;    public int getAge()&#123;        return age;    &#125;    public void setAge(int age)&#123;        this.age = age;    &#125;&#125;</span></span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootTest</span>   <span class="comment">// 用于测试的注解，可指定入口类或测试环境等@RunWith(SpringRunner.class) //在spring测试环境中进行测试public class propertTest &#123;    @Value(&quot;$&#123;age&#125;&quot;) // 获取配置文件中的age    private int age;    @Value(&quot;$&#123;name&#125;&quot;) // 获取配置文件中的name    private String name;    @Test  // 该注解表示一个测试方法    public void getAge()&#123;        System.out.println(age);    &#125;    @Test  // 该注解表示一个测试方法    public void getName()&#123;        System.out.println(name);    &#125;    @Autowired    private GetPersonInfoProperties getPersonInfoProperties;    @Test    public void getpersonproperties()&#123;        System.out.println(&quot;name:&quot; + getPersonInfoProperties.getName() +  &quot;;Age:&quot; + getPersonInfoProperties.getAge());    &#125;&#125;</span></span><br></pre></td></tr></table></figure>

<h4 id="实例4：演示如何使用application-priperties文件"><a href="#实例4：演示如何使用application-priperties文件" class="headerlink" title="实例4：演示如何使用application.priperties文件"></a>实例4：演示如何使用application.priperties文件</h4><p>编写配置项</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">com.example.nameYml=$&#123;nameYml:zhaoyao&#125;com.example.ageYml=30com.example.address[0]=杭州com.example.address[1]=南京com.example.address[2]=上海</span><br></pre></td></tr></table></figure>

<p>编写类文件处理配置项</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span> <span class="comment">//自动生成Setter、Getter、toString、equals、hashCode方法，以及不带参数的构造方法@Component //代表其是Spring管理类，常用在无法用@service、@Repository描述的Spring管理的类上，相当于通用的注解。它用于把普通POJO（简单的java对象）实例化到Spring容器中。当类不属于注解@controller和@Service等时，就可以使用注解@Component来标注这个类@ConfigurationProperties(prefix = &quot;com.example&quot;)public class CoExample &#123;    private String nameYml;    private int ageYml;    private List&lt;String&gt; address;&#125;</span></span><br></pre></td></tr></table></figure>

<p>编写测试，获取配置项的值</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootTest</span> <span class="comment">//用于测试的注解，可指定入口类或测试环境等@RunWith(SpringRunner.class) //在Spring测试环境中进行测试public class CoExampleTest &#123;    @Autowired  //自动注入    private CoExample coExample;    @Test    public void getNameYml()&#123;        System.out.println(coExample.getNameYml());    &#125;    @Test    public void getAgeYml()&#123;        System.out.println(coExample.getAgeYml());    &#125;    @Test    public void getAddress()&#123;        System.out.println(coExample.getAddress());    &#125;&#125;</span></span><br></pre></td></tr></table></figure>

<h4 id="实例5：配置多环境"><a href="#实例5：配置多环境" class="headerlink" title="实例5：配置多环境"></a>实例5：配置多环境</h4><p>不管是YML还是properties，都是在resources目录下新建3配置文件，分别表述测试环境（-dev）、生产环境（-prod）和主配置文件。通过主配置文件设置当前活动环境。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">spring.profiles.active=dev</span><br></pre></td></tr></table></figure>

<p>可以在运行JAR包时指定配置文件。如果要在启动时指定使用pro配置文件，则可以输入以下</p>
<figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">java -jar name.jar --spring.profile.active=prod</span><br></pre></td></tr></table></figure>

<h2 id="九、常用的starter"><a href="#九、常用的starter" class="headerlink" title="九、常用的starter"></a>九、常用的starter</h2><h1 id="Springboot学习笔记02"><a href="#Springboot学习笔记02" class="headerlink" title="Springboot学习笔记02"></a>Springboot学习笔记02</h1><h2 id="一、使用Thymeleaf"><a href="#一、使用Thymeleaf" class="headerlink" title="一、使用Thymeleaf"></a>一、使用Thymeleaf</h2><p>1、引入依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- thyemleaf依赖--&gt;</span><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>   <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>   <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-thymeleaf<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>2、在模板中加入解析  xmlns:th=”<a target="_blank" rel="noopener" href="http://www.thymeleaf.org&quot;/">http://www.thymeleaf.org&quot;</a></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span> <span class="attr">xmlns:th</span>=<span class="string">&quot;http://www.thymeleaf.org&quot;</span>&gt;</span><span class="tag">&lt;<span class="name">head</span>&gt;</span>    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span>    <span class="tag">&lt;<span class="name">title</span> <span class="attr">th:text</span>=<span class="string">&quot;$&#123;article.title&#125;&quot;</span>&gt;</span>标题<span class="tag">&lt;/<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">head</span>&gt;</span><span class="tag">&lt;<span class="name">body</span>&gt;</span><span class="tag">&lt;<span class="name">div</span> <span class="attr">th:text</span>=<span class="string">&quot;$&#123;article.title&#125;&quot;</span>&gt;</span>标题<span class="tag">&lt;/<span class="name">div</span>&gt;</span><span class="tag">&lt;<span class="name">div</span> <span class="attr">th:text</span>=<span class="string">&quot;$&#123;article.body&#125;&quot;</span>&gt;</span>内容<span class="tag">&lt;/<span class="name">div</span>&gt;</span><span class="tag">&lt;/<span class="name">body</span>&gt;</span><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>3、配置视图解析器</p>
<p>Springboot某人的页面映射路径（即模板文件存放的位置）为“classpath:/templates/*.html”。静态文件路径为“classpath:/static/”,其中可以存放层叠样式表CSS、JS等模板共用的静态文件。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"># 配置Thyemleaf模板解析器属性# 代表thymeleaf模式.由于thymeleaf检查HTML格式很严格，禁止这种严格的语法检查模式spring.thymeleaf.mode=LEGACYHTML5# 代表thymeleaf模式spring.thymeleaf.encoding=UTF-8# 代表文档类型spring.thymeleaf.servlet.content-type=text/html# 为了便于测试，在开发时需要关闭缓存spring.thymeleaf.cache=false</span><br></pre></td></tr></table></figure>

<h2 id="二、thymeleaf基础语法"><a href="#二、thymeleaf基础语法" class="headerlink" title="二、thymeleaf基础语法"></a>二、thymeleaf基础语法</h2><p>usingthymeleaf.pdf</p>
<h3 id="实例6：编写Thymeleaf视图以展示数据"><a href="#实例6：编写Thymeleaf视图以展示数据" class="headerlink" title="实例6：编写Thymeleaf视图以展示数据"></a>实例6：编写Thymeleaf视图以展示数据</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//MVC模式的控制器@Controller  //标注此控制器为MVC模式的控制器public class HelloWorldMvcController &#123;    @RequestMapping(&quot;/helloWorld&quot;)  //标注方法的URL映射路径“/helloWorld”    public String helloWorld(Model model) throws Exception&#123;        model.addAttribute(&quot;mav&quot;,&quot;Hello,Spring Boot!我是MVC结构！&quot;);        //视图（view）的位置和名称。视图位于example文件夹下，视图文件为hello.html        return &quot;example/hello&quot;;    &#125;&#125;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span> <span class="attr">xmlns:th</span>=<span class="string">&quot;http://www.thymeleaf.org&quot;</span>&gt;</span><span class="tag">&lt;<span class="name">head</span>&gt;</span>    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span>    <span class="tag">&lt;<span class="name">title</span> <span class="attr">th:text</span>=<span class="string">&quot;$&#123;mav&#125;&quot;</span>&gt;</span>mav<span class="tag">&lt;/<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">head</span>&gt;</span><span class="tag">&lt;<span class="name">body</span> <span class="attr">class</span>=<span class="string">&quot;container&quot;</span>&gt;</span><span class="tag">&lt;<span class="name">h1</span> <span class="attr">th:text</span>=<span class="string">&quot;$&#123;mav&#125;&quot;</span>&gt;</span>mav<span class="tag">&lt;/<span class="name">h1</span>&gt;</span><span class="tag">&lt;/<span class="name">body</span>&gt;</span><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="三、使用控制器"><a href="#三、使用控制器" class="headerlink" title="三、使用控制器"></a>三、使用控制器</h2><h3 id="1、常用注解及URL映射（窄化映射）"><a href="#1、常用注解及URL映射（窄化映射）" class="headerlink" title="1、常用注解及URL映射（窄化映射）"></a>1、常用注解及URL映射（窄化映射）</h3><p>注解@RequestMapping可以在类和方法上使用。如果在类上使用，则可以窄化映射。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span><span class="meta">@RequestMapping(&quot;news&quot;)</span><span class="function"><span class="keyword">public</span> class <span class="title">NewsController</span><span class="params">()</span></span>&#123;    <span class="comment">//GET方式    @RequestMapping(value=&quot;/&quot;,method=RequestMethod.GET)    public void add()&#123;&#125;    //POST方式    @RequestMapping(value=&quot;/&quot;,method=RequestMethod.POST)    public void save()&#123;&#125;&#125;// GET方式访问add方法的路径：http://localhost:8090/news///POST方式访问save方法的路径：http://localhost:8090/news///@GetMapping(&quot;/&quot;)它等价于@RequestMapping(value=&quot;/&quot;,method=RequestMethod.GET)//GetMapping:处理GET请求。//@PostMapping:处理POST请求。//@DeleteMapping:处理删除请求。//PutMapping:处理修改请求。</span></span><br></pre></td></tr></table></figure>

<h3 id="2、处理HTTP请求的方法"><a href="#2、处理HTTP请求的方法" class="headerlink" title="2、处理HTTP请求的方法"></a>2、处理HTTP请求的方法</h3><p>RequestMapping的method类型有GET、HEAD、POST、PUT、PATCH、DELETE、OPTIONS、TRACE。可以通过这些method来处理前端用不同方法提交的数据。</p>
<ul>
<li><p>GET：获取资源，如以下代码用GET方法根据id来获取文章对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;/&#123;id&#125;&quot;)</span><span class="function"><span class="keyword">public</span> ModelAndView <span class="title">getArticle</span><span class="params">(<span class="meta">@PathVariable(&quot;id&quot;)</span> Integer id)</span> <span class="keyword">throws</span> Exception</span>&#123;    Article articles = articleRepository.findNyId(id);    ModelAndView mav = <span class="keyword">new</span> ModelAndView(<span class="string">&quot;article/show&quot;</span>);    mav.addObject(<span class="string">&quot;article&quot;</span>,articles);    <span class="keyword">return</span> mav;&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>DELETE：在使用Restful风格则需要使用DELETE方法。在使用DELETE方法删除资源时，要注意判断是否成功，因为返回VOID类型。</p>
<p>一般有一下三种方法进行判断：</p>
<ul>
<li>使用try catch exception：如果不发生异常，则默认为成功，但是这样并不好。</li>
<li>通过存储过程返回值来判断是否正确执行：如果执行成功，则返回1或在大于0 的值；如果执行失败，则返回0.</li>
<li>在执行DELETE方法前先查询是否有数据：在执行DELETE方法后返回值是0，所以，一般先查询一下是否有数据。</li>
</ul>
</li>
<li><p>POST：如果需要添加对象，那一般使用POST方法传递一个Model对象。</p>
</li>
<li><p>PUT：如果对象需要更新，则用PUT方法发送请求。</p>
</li>
<li><p>PATCH：是一个新引入的方法，是对PUT方法的补充，用来对已知资源进行局部更新。</p>
</li>
<li><p>OPTIONS：该方法用于获取当前URL。若请求成功，则会在HTTP头中包含一个名为“Allow”的头，其值是所支持的方法，如值为“GET，POST”。它还允许客户端查看服务器的性能。如果遇到“500错误”，则OPTIONS不进行第二次请求。</p>
</li>
<li><p>TRACE：它显示服务器收到的请求，主要用于测试或诊断。</p>
</li>
</ul>
<h3 id="3、处理内容类型"><a href="#3、处理内容类型" class="headerlink" title="3、处理内容类型"></a>3、处理内容类型</h3><h4 id="3-1、认识HTTP中的媒体类型Content-Type"><a href="#3-1、认识HTTP中的媒体类型Content-Type" class="headerlink" title="3.1、认识HTTP中的媒体类型Content-Type"></a>3.1、<strong>认识HTTP中的媒体类型Content-Type</strong></h4><p>（1）常见的媒体格式如下：</p>
<ul>
<li>text/html：HTML格式</li>
<li>text/plain：纯文本格式</li>
<li>text/xml：XML格式</li>
<li>image/gif：GIF图片格式</li>
<li>image/jpeg：JPG图片格式</li>
<li>image/png：PNG图片格式</li>
</ul>
<p>（2）以application开头的媒体格式如下：</p>
<ul>
<li>application/xhtml+xml：XHTML+XML格式</li>
<li>application/xml：XML数据格式</li>
<li>application/atom+xml：Atom XML聚合格式</li>
<li>application/json：JSON数据格式</li>
<li>application/pdf：PDF格式</li>
<li>application/msword：Word文档格式</li>
<li>application/octet-stream：二进制流数据（常用于文件下载）</li>
<li>application/x-www-form-urlencoded：表单数据编码方式，<form enctype>只默认的ecType，form(表单)数据被默认编码为key/value格式发送给服务器。</form></li>
<li>multipart/from-data：如果在表单中进行文件上传，则需要使用该格式</li>
</ul>
<h4 id="3-2、使用Produces和Consumes处理内容类型"><a href="#3-2、使用Produces和Consumes处理内容类型" class="headerlink" title="3.2、使用Produces和Consumes处理内容类型"></a>3.2、<strong>使用Produces和Consumes处理内容类型</strong></h4><p>（1）Produces的例子</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span><span class="meta">@RequestMapping(value=&quot;/&#123;id&#125;&quot;,method=RequestMethod.GET,produces=&quot;appliction/json&quot;)</span>  <span class="comment">//返回json的话可以省略produces属性，因为RestController就是返回jsonpublic Mdoel getModel(@PathVariable String id, Model model)&#123;    //&#125;</span></span><br></pre></td></tr></table></figure>

<p>如果要强制返回编码，则加上编码类型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">produces = <span class="string">&quot;MediaType.APPLICATION_JSON_VALUE&quot;</span>+<span class="string">&quot;;charset=utf-8&quot;</span>)</span><br></pre></td></tr></table></figure>

<p>（2）Consumes的例子</p>
<p>在以下例子中，Consumes是消费者，用于指定获取消费者的数据类型。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span><span class="meta">@RequestMapping(value=&quot;/&#123;id&#125;&quot;,method=RequestMethod.POST,produces=&quot;appliction/json&quot;)</span>  <span class="comment">//返回json的话可以省略produces属性，因为RestController就是返回jsonpublic void addModel(@RequestBody Model model)&#123;    //&#125;</span></span><br></pre></td></tr></table></figure>

<h4 id="3-3、在方法中使用参数"><a href="#3-3、在方法中使用参数" class="headerlink" title="3.3、在方法中使用参数"></a>3.3、<strong>在方法中使用参数</strong></h4><p>1、获取路径中的值</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**  * Description: 根据id获取文章对象  * http://localhost/article/123  * 程序获取路径中123的值  */</span><span class="meta">@GetMapping(&quot;article/&#123;id&#125;&quot;)</span><span class="function"><span class="keyword">public</span> ModelAndView <span class="title">getArticle</span><span class="params">(<span class="meta">@PathVariable(&quot;id&quot;)</span> Integer id)</span></span>&#123;    Article articles = articleRepository.findById(id);    ModelAndView mav = <span class="keyword">new</span> ModelAndView(<span class="string">&quot;article/show&quot;</span>);    mav.addObject(<span class="string">&quot;article&quot;</span>,articles);    <span class="keyword">return</span> mav;&#125;</span><br></pre></td></tr></table></figure>

<p>2、获取路径中的参数</p>
<p>对于路径中的参数获取，可以写入方法的形参中。下面代码是获取参数username的值</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;/addUser&quot;)</span><span class="function"><span class="keyword">public</span> String <span class="title">addUser</span><span class="params">(String username)</span></span>&#123;    &#125;<span class="comment">//这里的参数和上面所讲的获取路径值是不一样的，比如http://localhost/user/?username=zhaoyao，它是由“=”隔开的</span></span><br></pre></td></tr></table></figure>

<p>3、通过Bean接收HTTP提交的对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Stirng <span class="title">addUser</span><span class="params">(UserModel user)</span></span></span><br></pre></td></tr></table></figure>

<p>4、用注解@ModelAttribute获取参数</p>
<p>用于从Model、Form或URL请求参数中获取属性值</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value=&quot;/addUser&quot;,method=RequestMethod.POST)</span><span class="function"><span class="keyword">public</span> String <span class="title">addUser</span><span class="params">(<span class="meta">@ModelAttribute(&quot;user&quot;)</span> UserMdoel user)</span></span></span><br></pre></td></tr></table></figure>

<p>5、通过HttpServletRequest接收参数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;/addUser&quot;)</span><span class="function"><span class="keyword">public</span> String <span class="title">addUser</span><span class="params">(HttpServletRequest request)</span></span>&#123;    System.out.println(<span class="string">&quot;name:&quot;</span>+request.GETParameter(<span class="string">&quot;username&quot;</span>));    <span class="keyword">return</span> <span class="string">&quot;/index&quot;</span>;&#125;</span><br></pre></td></tr></table></figure>

<p>6、用@RequestParam绑定入参</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//当请求参数不存在时会有异常发生，可以通过设置属性“required=false”来解决@RequestParam(value=&quot;username&quot;,required=false)</span></span><br></pre></td></tr></table></figure>

<p>7、用@RequestBody接收JSON数据</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value=&quot;adduser&quot;,method=&#123;RequestMethod.POST&#125;)</span><span class="meta">@ResponseBodypublic</span> <span class="function"><span class="keyword">void</span> <span class="title">saveUser</span><span class="params">(<span class="meta">@RequestBody</span> List&lt;User&gt; users)</span></span>&#123;    &#125;</span><br></pre></td></tr></table></figure>

<p>8、上传文件MultipartFile</p>
<p>通过@RequestParam获取文件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">singleFileUpload</span><span class="params">(<span class="meta">@RequestParam(&quot;file&quot;)</span>MultipartFile file, RedireAttributes redireAttributes)</span></span>&#123;    <span class="keyword">if</span>(file.isEmpty())&#123;        redireAttributes.addFlashAttribute(<span class="string">&quot;message&quot;</span>,<span class="string">&quot;请选择文件&quot;</span>);        <span class="keyword">return</span> <span class="string">&quot;redirect:uploadStatus&quot;</span>;    &#125;    <span class="keyword">try</span>&#123;        <span class="keyword">byte</span>[] bytes = file.getBytes();        Path path = Paths.get(UPLOAD_FOLDER+file.getOriginalFilename());        Files.write(path,bytes);        redireAttributes.addFlashAttribute(<span class="string">&quot;message&quot;</span>,<span class="string">&quot;成功上传 &quot;</span> + file.getOriginalFilename() + <span class="string">&quot;&quot;</span>);    &#125;    <span class="keyword">catch</span>(IOException e)&#123;        e.printStackTrace();    &#125;    <span class="keyword">return</span> <span class="string">&quot;redirect:/uploadStatus&quot;</span>;&#125;<span class="comment">//出于安全考虑，在生产环境中需要判断文件的类型，一般不允许上传“exe”等格式的可执行文件</span></span><br></pre></td></tr></table></figure>

<p>9、上传图片</p>
<p>这里以常用的CKEditor4.10.1为例，实现上传图片功能。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> l=System.currentTimeMillis();<span class="comment">//新建日期对象Date date= new Date(l)；//转换日期输出格式SimpleDateFromat dateFormat = new SimpleDateFormat(&quot;yyyyMMdd&quot;);String nyr = dateFormat.format(date);private static String UPLOADED_FOLDER=&quot;/UPLOADED/img/&quot;;@PostMapping(&quot;/upload&quot;)@ResponseBody//注意，ckeditor上传的是upload字段public Map&lt;String,Object&gt; singleFileUpload(@RequestParam(&quot;upload&quot;) MultipartFile file, RedirectAttributes redirectAttributes)&#123;    Map&lt;String,Object&gt; map = new HashMap&lt;String,Object&gt;();    if(file.getOriginalFilename().endsWith(&quot;.jpg&quot;) || file.getOriginalFilename().endsWith(&quot;.png&quot;) ||  file.getOriginalFilename().endsWith(&quot;.gif&quot;) )&#123;        try&#123;            byte[] bytes = file.getBytes();            String S = nyr + Math.random() + file.getOriginalFilename();            Path path = Paths.get(UPLOADED_FOLDER + S);            Files.write(path,bytes);            map.put(&quot;uploaded&quot;,1);            map.put(&quot;fileName&quot;,S);            map.put(&quot;url&quot;,&quot;/UPLOAD/img/&quot;+S);            map.put(&quot;message&quot;,&quot;上传成功&quot;);            return map;        &#125;catch (IOException e)&#123;            e.printStackTrace();        &#125;    &#125;    else&#123;        map.put(&quot;uploaded&quot;,0);        map.put(&quot;fileName&quot;.file.getOriginalFilename());        map.put(&quot;url&quot;,&quot;/img/&quot;+file.getOriginalFilename());        map.put(&quot;message&quot;,&quot;图片后缀只支持png,jpg,gif,请检查！&quot;);        return map;    &#125;    return map;&#125;</span></span><br></pre></td></tr></table></figure>

<h4 id="3-4、实例7-实现MVC模式的Web应用程序"><a href="#3-4、实例7-实现MVC模式的Web应用程序" class="headerlink" title="3.4、实例7:实现MVC模式的Web应用程序"></a>3.4、实例7:实现MVC模式的Web应用程序</h4><ul>
<li><p>添加依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-thymeleaf<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span>    <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></li>
<li><p>创建实体模型</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Datapublic</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;    <span class="comment">//定义id    private long id;    //定义用户名    private String name;    //定义年龄    private int age;&#125;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>创建控制器</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controllerpublic</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;    <span class="comment">//映射URL地址    @GetMapping(&quot;/user&quot;)    public ModelAndView user()&#123;        //实例化对象        User user= new User();        user.setName(&quot;zhaoyao&quot;);        user.setAge(29);        //定义MVC中的视图模板        ModelAndView modelAndView = new ModelAndView(&quot;user&quot;);        //传递user实体对象给视图        modelAndView.addObject(&quot;user&quot;,user);        return modelAndView;    &#125;&#125;</span></span><br></pre></td></tr></table></figure>

<ul>
<li><p>创建用于展示的视图</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;&lt;!--thymeleaf模板支持--&gt;&lt;html lang=<span class="string">&quot;en&quot;</span> xmlns:th=<span class="string">&quot;http://www.thymeleaf.org&quot;</span>&gt;&lt;head&gt;    &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;    &lt;meta name=<span class="string">&quot;viewport&quot;</span> content=<span class="string">&quot;width=device-width,initial-scale=1.0&quot;</span>&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;    &lt;!--显示由控制器传递过来的实体user的值--&gt;    &lt;!--<span class="comment">/*@thymesVar id=&quot;user&quot; type=&quot;&quot;*/</span>--&gt;    &lt;div th:text=<span class="string">&quot;$&#123;user.name&#125;&quot;</span>&gt;&lt;/div&gt;    &lt;div th:text=<span class="string">&quot;$&#123;user.age&#125;&quot;</span>&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</span><br></pre></td></tr></table></figure></li>
</ul>
<h4 id="3-5、实例8：验证表单数据并实现数据的自定义验证"><a href="#3-5、实例8：验证表单数据并实现数据的自定义验证" class="headerlink" title="3.5、实例8：验证表单数据并实现数据的自定义验证"></a>3.5、实例8：验证表单数据并实现数据的自定义验证</h4><p>具体查看个人码云上项目名称thymeleaf</p>
<h1 id="springboot学习笔记03"><a href="#springboot学习笔记03" class="headerlink" title="springboot学习笔记03"></a>springboot学习笔记03</h1><h2 id="一、响应式编程"><a href="#一、响应式编程" class="headerlink" title="一、响应式编程"></a>一、响应式编程</h2><p>1、响应式Web框架WebFlux。WebFlux可以在资源有限的情况下提高系统的吞吐量和伸缩性（不是提高性能）。这意味着，在资源相同的情况下，WebFlux可以处理更多的请求（不是业务）。</p>
<p>2、总结：MVC能满足的场景，就不需要改用WebFlux。WebFlux和MVC可以混合使用。如果开发I/O密集型服务，则可以选择用WebFlux实现。</p>
<p>3、如果在pom.xml文件中同时引用了spring-boot-starter-web和spring-boot-starter-webflux依赖，则优先使用spring-boot-starter-web。控制台输出的启动日志会提示“Tomcat started on port(s):….”，而使用WebFlux会提示“Netty started on port”。</p>
<p><strong>4、Flux 和 Mono 是异步编程框架 Reactor 中的两种基本类型，而Spring Webflux 是基于 Reactor 构建的。Flux 表示空或多个结果，Mono 表示空或一个结果。两者可以进行转换，对一个Flux序列进行计数操作时，得到的结果是一个Mono<Long>对象。把多个Mono序列合并在一起，得到的是一个Flux对象。</Long></strong></p>
<p>5、开发WebFlux的流程</p>
<ul>
<li><p>响应式开发流程</p>
<ul>
<li>创建Handler类。这里的Handler类相当于Spring MVC的Controller层中的方法体。在响应式编程中，请求和响应不再是HttpServletRequest和HttpServletResponse，而是编程了ServerRequest和ServerResponse。</li>
<li>配置RouterFunction。RouterFunction和注解@RequestMapping相似，都用于提供URL路径。RouterFunction的格式也是固定的，第1个参数代表路径，第2个参数代表方法，合起来代表将URL映射到方法。</li>
</ul>
</li>
<li><p>注解式开发流程</p>
<p>注解式开发方式只是Spring团队为了更好地迁移而提供的。和MVC开发模式一样，地址映射也是通过@RequestMapping提供的，用@Controller或@Restcontroller来代替Handler类。</p>
</li>
</ul>
<p>由于个人对WebFlux的需求不大，此框架实例代码不做笔记，仙剑实例9、10、11见个人码云。</p>
<h2 id="二、实例12：用WebFlux模式操作MongoDB数据库，实现数据的增加、删除、修改和查询功能"><a href="#二、实例12：用WebFlux模式操作MongoDB数据库，实现数据的增加、删除、修改和查询功能" class="headerlink" title="二、实例12：用WebFlux模式操作MongoDB数据库，实现数据的增加、删除、修改和查询功能"></a>二、实例12：用WebFlux模式操作MongoDB数据库，实现数据的增加、删除、修改和查询功能</h2><p><img src="/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011184319065.png" alt="image-20211011184319065"></p>
<h3 id="1、下载安装MongoDB-4-4-4-以及oto-3T-1-4"><a href="#1、下载安装MongoDB-4-4-4-以及oto-3T-1-4" class="headerlink" title="1、下载安装MongoDB 4.4.4 以及oto 3T -1.4"></a>1、下载安装MongoDB 4.4.4 以及oto 3T -1.4</h3><h3 id="2、创建用户名、密码及数据库表"><a href="#2、创建用户名、密码及数据库表" class="headerlink" title="2、创建用户名、密码及数据库表"></a>2、创建用户名、密码及数据库表</h3><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--打开mongo.exe,切换到adminuse admin--创建用户名、密码和角色 db.createUser(&#123;user:&quot;geiao&quot;,pwd:&quot;1163117842@qqcom&quot;,roles:[&quot;root&quot;]&#125;)   db.changeUserPassword(&#123;user:&quot;geiao&quot;,pwd:&quot;123456789&quot;,roles:[&quot;root&quot;]&#125;)</span></span><br></pre></td></tr></table></figure>

<p><img src="/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011174643868.png" alt="image-20211011174643868"></p>
<h3 id="3、pom-xml添加依赖"><a href="#3、pom-xml添加依赖" class="headerlink" title="3、pom.xml添加依赖"></a>3、pom.xml添加依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- MongoDB--&gt;</span><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-mongodb-reactive<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="4、配置文件中添加连接"><a href="#4、配置文件中添加连接" class="headerlink" title="4、配置文件中添加连接"></a>4、配置文件中添加连接</h3><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># MongoDB  spring.data.mongodb.uri=mongodb://用户名：密码@ip地址:端口号/数据库spring.data.mongodb.uri=mongodb://geiao:1163117842@qqcom@localhost:27017/test</span></span><br></pre></td></tr></table></figure>

<h3 id="5、entity→User-java"><a href="#5、entity→User-java" class="headerlink" title="5、entity→User.java"></a>5、entity→User.java</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span><span class="meta">@AllArgsConstructor</span><span class="meta">@NoArgsConstructorpublic</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;    <span class="comment">//定义主键id    private String id;    //定义用户名    @NotBlank(message = &quot;用户名不能为空&quot;)    @Length(min = 5,max = 20, message=&quot;用户名称长度为5-20个字符&quot;)    private String name;    //定义年龄    @NotNull(message = &quot;年龄不能为空&quot;)    @Min(value = 18,message = &quot;最小18岁&quot;)    @Max(value = 100,message = &quot;最大100岁&quot;)    private Integer age;    @Email(message = &quot;请输入邮箱&quot;)    @NotBlank(message = &quot;邮箱不能为空&quot;)    private String email;    @MyConstraint    private String answer;&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="6、repository→UserRepository-java"><a href="#6、repository→UserRepository-java" class="headerlink" title="6、repository→UserRepository.java"></a>6、repository→UserRepository.java</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserRepository</span> <span class="keyword">extends</span> <span class="title">ReactiveMongoRepository</span>&lt;<span class="title">User</span>, <span class="title">String</span>&gt; </span>&#123;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="7、controller→UserWebFluxController"><a href="#7、controller→UserWebFluxController" class="headerlink" title="7、controller→UserWebFluxController"></a>7、controller→UserWebFluxController</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span><span class="meta">@RequestMapping(path = &quot;/userWebFlux&quot;)</span><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserWebFluxController</span> </span>&#123;    <span class="meta">@Autowired</span>    <span class="keyword">private</span> UserRepository userRepository;    <span class="meta">@GetMapping(&quot;/listMongoDB&quot;)</span>    <span class="function"><span class="keyword">public</span> Flux&lt;User&gt; <span class="title">getAll</span><span class="params">()</span></span>&#123;        <span class="keyword">return</span> userRepository.findAll();    &#125;    <span class="comment">//启动测试就可以发现查询是一个一个出来的，而不是一下返回。    @GetMapping(value = &quot;/listdelay&quot;, produces = MediaType.APPLICATION_JSON_VALUE)    public Flux&lt;User&gt; getAlldelay()&#123;        return userRepository.findAll().delayElements(Duration.ofSeconds(1));    &#125;    @GetMapping(&quot;/&#123;id&#125;&quot;)    public Mono&lt;ResponseEntity&lt;User&gt;&gt; getUser(@PathVariable String id) &#123;        return userRepository.findById(id)                .map(getUser -&gt; ResponseEntity.ok(getUser))                .defaultIfEmpty(ResponseEntity.notFound().build());    &#125;    @PostMapping(&quot;&quot;)    public Mono&lt;User&gt; createUser(@Valid User user)&#123;        return userRepository.save(user);    &#125;    @PutMapping(&quot;/&#123;id&#125;&quot;)    public Mono updateUser(@PathVariable(value = &quot;id&quot;) String id, @Valid User user)&#123;        return userRepository.findById(id)                .flatMap(existingUser -&gt;&#123;                    existingUser.setName(user.getName());                    return userRepository.save(existingUser);                &#125;)                .map(updateUser -&gt; new ResponseEntity&lt;&gt;(updateUser, HttpStatus.OK))                .defaultIfEmpty(new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND));    &#125;    @DeleteMapping(&quot;/&#123;id&#125;&quot;)    public Mono&lt;ResponseEntity&lt;Void&gt;&gt; deleteUser(@PathVariable(value = &quot;id&quot;) String id)&#123;        return userRepository.findById(id)                .flatMap(existingUser -&gt;                        userRepository.delete(existingUser)                            .then(Mono.just(new ResponseEntity&lt;Void&gt;(HttpStatus.OK)))                )                .defaultIfEmpty(new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND));    &#125;&#125;</span></span><br></pre></td></tr></table></figure>

<p>8、测试接口</p>
<ul>
<li>根据id查询</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost:8090/userWebFlux/6066c330945856c2309af2b6</span><br></pre></td></tr></table></figure>

<p><img src="/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011174711784.png" alt="image-20211011174711784"></p>
<ul>
<li>新增测试</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">localhost:8090/userWebFlux?id=1&amp;name=geiao1&amp;age=21&amp;email=1111111@qq.com&amp;answer=北京</span><br></pre></td></tr></table></figure>

<p><img src="/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011174734925.png" alt="image-20211011174734925"></p>
<ul>
<li>根据Id更新数据</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">localhost:8090/userWebFlux/6066c330945856c2309af2b6?id=&quot;2&quot;&amp;name=zhangsan&amp;age=38&amp;email=1163117842@qq.com&amp;answer=上海</span><br></pre></td></tr></table></figure>

<p><img src="/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/image-20211011174800640.png" alt="image-20211011174800640"></p>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://giscloud.ltd/2021/10/11/springboot%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" title="Springboot学习笔记" target="_blank" rel="external">https://giscloud.ltd/2021/10/11/springboot学习笔记/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://github.com/geiao223" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://github.com/geiao223" target="_blank"><span class="text-dark">耀</span><small class="ml-1x">GIS Developer</small></a></h3>
        <div>低头一片黑暗，抬头一片光明。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
           
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/2021/10/13/cas/" title="CAS"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/2021/10/11/test/" title="Test"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button">
        <span>[&nbsp;</span><span>文章目录</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span>]</span>
      </a>
    </li>
    
  </ul>
  
  
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal" data-target="#donateModal"><span>赏</span></button>
  <!-- <div class="wave-icon wave-icon-danger btn-donate" data-toggle="modal" data-target="#donateModal">
    <div class="wave-circle"><span class="icon"><i class="icon icon-bill"></i></span></div>
  </div> -->
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat" data-mobile-sites="weibo,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  
<!-- Modal -->
<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content donate">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div class="modal-body">
        <div class="donate-box">
          <div class="donate-head">
            <p>感谢您的支持，我会继续努力的!</p>
          </div>
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="alipay">
              <div class="donate-payimg">
                <img src="/images/donate/alipayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开支付宝扫一扫，即可进行扫码打赏哦</p>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="wechatpay">
              <div class="donate-payimg">
                <img src="/images/donate/wechatpayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开微信扫一扫，即可进行扫码打赏哦</p>
            </div>
          </div>
          <div class="donate-footer">
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay" aria-expanded="true"><i class="icon icon-alipay"></i> 支付宝</a>
              </li>
              <li role="presentation" class="">
                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab" aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i> 微信支付</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>



</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	<head>
    <meta charset="utf-8">
    
      
            
        
            
        
            
        
            
              <link rel="stylesheet" href="//at.alicdn.com/t/font_557201_kt8eehtlfzr.css">
            
        
            
        
    
</head>

	
    <ul class="social-links">
    	
            
                <li><a href="https://github.com/geiao223" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
            
             
        
            
                <li><a href="https://gitee.com/geiao2" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
            
             
        
            
                <li><a href="https://www.zhihu.com/people/geiao1314/columns" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
            
             
        
            
            
                <li><a href="https://space.bilibili.com/315638226" target="_blank" title="Bilibili" data-toggle=tooltip data-placement=top><i class="iconfont icon-bilibili-line"></i></a></li>
             
        
            
                <li><a href="https://mail.google.com/mail/u/0/?fs=1&tf=cm&source=mailto&to=zhaoyao92@qq.com" target="_blank" title="Email" data-toggle=tooltip data-placement=top><i class="icon icon-email"></i></a></li>
            
             
        
    </ul>

    <div class="copyright">
    	
        <!-- <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div> -->
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/js/plugin.min.js"></script>


<script src="/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/js/insight.js"></script>






   




   
    
  <!-- <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"> -->
  <script src="//cdn.jsdelivr.net/npm/gitalk@1.4.0/dist/gitalk.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/blueimp-md5@2.10.0/js/md5.min.js"></script>
  <script type="text/javascript">
  var gitalk = new Gitalk({
    clientID: '66af9719abdb92e5034a',
    clientSecret: '3ca9af86aec721cc878a615c07939f8ed2290460',
    repo: 'blog-comments',
    owner: 'geiao223',
    admin: ['geiao223'],
    proxy: 'https://shielded-brushlands-08810.herokuapp.com/https://github.com/login/oauth/access_token',
    id: md5(location.pathname),
    distractionFreeMode: true
  })
  gitalk.render('comments')
  </script>

      



  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.3.5/dist/jquery.fancybox.min.js"></script>
  <script>
  //利用 FancyBox 实现点击图片放大
  $(document).ready(function() {
    $('article img').not('[hidden]').not('.panel-body img').each(function() {
      var $image = $(this);
      var imageCaption = $image.attr('alt');
      var $imageWrapLink = $image.parent('a');
      if ($imageWrapLink.length < 1) {
        var src = this.getAttribute('src');
        var idx = src.lastIndexOf('?');
        if (idx != -1) {
          src = src.substring(0, idx);
        }
        $imageWrapLink = $image.wrap('<a href="' + src + '"></a>').parent('a');
      }
      $imageWrapLink.attr('data-fancybox', 'images');
      if (imageCaption) {
        $imageWrapLink.attr('data-caption', imageCaption);
      }
    });
    $().fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: false,
    });
  });
  </script>





<div id="go-top"></div>
<style type="text/css">
#go-top {
 width:40px;height:36px;
 background-color:#777;
 position:relative;
 border-radius:2px;
 position:fixed;right:10px;bottom:60px;
 cursor:pointer;display:none;
}
#go-top:after {
 content:" ";
 position:absolute;left:14px;top:14px;
 border-top:2px solid #fff;border-right:2px solid #fff;
 width:12px;height:12px;
 transform:rotate(-45deg);
}
#go-top:hover {
 background-color:#333;
}
</style>
<script>
$(function () {
  var top=$("#go-top");
  $(window).scroll(function () {
    ($(window).scrollTop() > 300) ? top.show(300) : top.hide(200);
    $("#go-top").click(function () {
      $('body,html').animate({scrollTop:0});
      return false();
    })
  });
});
</script>  
</body>
</html>